package com.bit.blog.common.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Map;
@Slf4j
//JWT自己实现的相关工具类；
public class JwtUtils {
    private static String SECRET_STRING="ye+z98FVBdx1rXqI0dZSRh8kGKDId2DPxqVYC2Vt8M0=";
    private static Key key=Keys.hmacShaKeyFor(Decoders.BASE64.decode(SECRET_STRING));
    public static String genToken(Map<String, Object> claims){
        String compact= Jwts.builder()
                .setClaims(claims)
                .signWith(key)
                .compact();
        return compact;
    }
    //进行校验token 的正确性；
    public static Claims parseToken(String token){
        //token为空串的话
        if(!StringUtils.hasLength(token)){
            return null;
        }
        JwtParser build=Jwts.parserBuilder().setSigningKey(key).build();
        Claims claims=null;
        try {
            claims=build.parseClaimsJws(token).getBody();
        }catch (Exception e){
            log.error("token解析失败，token:"+token);
        }
        return claims;
    }
//    public static void main(String[] args){
////        String token=null;
// String token="eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiMTIzNDU2IiwiaWQiOiJ6aGFuZ3NhbiJ9.E-WkeWi892tUMaIHHecx8iTowRpHB5-oAqL1pASZ_KE";
//        Claims claims=parseToken(token);
//        System.out.println(token);
//    }
}
